<template>
	<view :style="skin" class="content login">
		<view class="headline">
			{{$t('login.DearAgent')}}<br />
			{{$t('login.welcomeback')}}
		</view>
		<view class="formBox">
			<!-- 账号登录 -->
			<text class="u-demo-block__title">{{$t('login.phoneNumber')}}</text>
			<view class="u-demo-block__content">
				<u-input v-model="userObj.userName" border="bottom" :placeholder="$t('login.inputPhone')">
				</u-input>
			</view>

			<text class="u-demo-block__title">{{$t('login.password')}}</text>
			<view class="u-demo-block__content">
				<u-input v-model="userObj.pass" border="bottom" :password="true" :placeholder="$t('login.inputPass')">

				</u-input>
			</view>
		</view>


		<view class="btnModule">
			<u-button color="var(--subjectColor)" @click="loginSkip">{{$t('login.login')}}
			</u-button>

			<!-- 		<u-button color="var(--subjectColor)" @click="handleGoole">{{$t('login.login')}}
			</u-button> -->
		</view>

		<view class="modelChange">
			<text @click="resetPsd">{{$t('login.Forgotpassword')}}</text>
		</view>

		<view class="footer">
			<view class="tips">
				<text>
					{{$t('login.noAccount')}}
				</text>
				<text class="tipsColor" @click="handleRegister"> {{$t('login.Registernow')}}</text>
			</view>
			<view class="tips">
				V{{version}}
			</view>
			<fui-safe-area background="#F8F8F8"></fui-safe-area>
		</view>


	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	import {
		login,
		logout
	} from '@/api/login.js'
	import {
		userMemList,
		gtUdetails
	} from '@/api/user.js'
	import {
		getModelList
	} from '@/api/modelList.js'
	import {
		leaFixPricePage
	} from '@/api/leaFixPrice.js'
	import {
		liststockbind
	} from '@/api/deviceList.js'
	import {
		encryption,
		deepClone,
	} from '@/utils/index.js'
	import {
		addUser,
		cratetable,
		delDBUser,
		delDBdeviceInfo,
		delDBdeviceType,
		delDBlease,
		delDBmoney,
		delDBprice,
		delDBpassConfig
	} from '@/utils/sql/sqlUser.js'
	import {
		crateLease,
		delLease,
		addLease,
		delLeasePid
	} from '@/utils/sql/sqllease.js'
	import {
		addDeviceType
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		addDevice,
		getInStoreArr,
		delDeviceInfo
	} from '@/utils/sql/sqlDevice.js'
	import {
		addPrice
	} from '@/utils/sql/sqlPrice.js'
	import {
		addOrUpdateMoney
	} from '@/utils/sql/sqlMoney.js'
	import {
		filteredObject
	} from '@/utils/index.js'
	import {
		gtTotal
	} from '@/api/balance.js'
	import {
		leasebdatas,
		userbdatasuser,
		initdatas
	} from '@/api/leaData.js'
	export default {
		data() {
			return {
				version: '1.0.0',
				showAccount: false,
				isLogin: false,
				loginList: [],
				database: {},
				tableArr: [],
				userObj: {
					// userName: '15678374856',
					// pass: '123456',
					userName: '',
					pass: '',
				},
				sync_flag: 0,
			}
		},
		onShow() {
			let that = this
			let overdueLogin = uni.getStorageSync('overdueLogin')
			if (overdueLogin) {
				uni.showToast({
					title: that.$t('login.ExpiredAgain'),
					duration: 2000,
					icon: 'none'
				})
			}
			uni.setStorageSync('overdueLogin', false);

			let obj = uni.getSystemInfoSync()
			console.log(obj);
			this.version = obj.appVersion
			// this.versionCode = obj.appVersionCode
		},

		methods: {
			handleGoole() {
				uni.navigateTo({
					url: '/pages/login/googleMap/googleMap?type=3'
					// url:'/pages/googleWebView/googleWebView'
				})
			},
			handleRegister() {
				uni.navigateTo({
					url: '/pages/login/mobileRegister/mobileRegister?type=1'
				})
			},
			resetPsd() {
				uni.navigateTo({
					url: '/pages/login/resetPass/resetPass'
				})
			},
			loginSkip() {
				let that = this
				if (!this.userObj.userName) {
					uni.showToast({
						title: that.$t('login.PleaseAccount'),
						icon: 'none'
					})
					return false
				}
				if (!this.userObj.pass) {
					uni.showToast({
						title: that.$t('login.PleasePassword'),
						icon: 'none'
					})
					return false
				}

				uni.showLoading({
					title: that.$t('login.logining'),
					icon: 'loading'

				});
				if (this.isLogin) {
					return
				}
				this.sync_flag = 0;
				this.isLogin = true;
				
				// 需要原生插件支持
				plus.android.importClass("android.provider.Settings");
				const context = plus.android.runtimeMainActivity().getApplicationContext();
				const androidId = plus.android.invoke("android.provider.Settings$Secure", "getString", context
					.getContentResolver(), "android_id");
				console.log("Android ID: ", androidId);
				
				
				login({
					username: this.userObj.userName,
					password: encryption(this.userObj.pass),
					mac:androidId,
				}).then(async res => {
					console.log(res);
					this.isLogin = false
					if (res.code == 0) {
						this.sync_flag++;
						console.log(1);
						uni.setStorageSync('sync_flag', this.sync_flag);

						uni.setStorageSync('expires_in', res.data.expires_in) //单位秒
						uni.setStorageSync('accessToken', res.data.access_token)
						uni.setStorageSync('refreshToken', res.data.refresh_token)
						uni.setStorageSync('logintimestamp', Math.round(new Date() / 1000))

						let uRes = await gtUdetails();
						console.log(uRes);
						if (uRes.code == 0) {
							this.sync_flag++;
							console.log(2);
							uni.setStorageSync('sync_flag', this.sync_flag);
							uni.setStorageSync('loginInfo', JSON.stringify(uRes.data))


							this.database = {
								name: this.userObj.userName, //数据库
								path: `_doc/${this.userObj.userName}.db`, //数据库地址
							}
							uni.setStorageSync('database', this.database)

							this.setDB()

						}


					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						// if (res.data == 2) {
						// 	uni.hideToast();

						// 	uni.navigateTo({
						// 		url: '/pages/login/audit/audit'
						// 	})
						// }
					}
				})



			},
			// 设置本地数据库
			async setDB() {
				await this.openDB();
				await this.delDB();
				await this.createDB()


			},
			// 登录前清空数据表，释放账号没有做清除退出登录操作
			async delDB() {
				let res11 = await delDBUser()
				let res22 = await delDBdeviceInfo()
				let res33 = await delDBdeviceType()
				let res44 = await delDBlease()
				let res55 = await delDBmoney()
				let res66 = await delDBprice()
				let res77 = await delDBpassConfig()
			},
			async createUser() {

				let res = await userMemList();
				if (res.code == 0) {

					this.sync_flag++;
					console.log(3);
					uni.setStorageSync('sync_flag', this.sync_flag);

					let uRes = await initdatas();
					if (uRes.code == 0) {
						this.sync_flag++;
						console.log(4);
						uni.setStorageSync('sync_flag', this.sync_flag);

						let uArr = uRes.data.user == null ? [] : uRes.data.user
						let serveArr = res.data == null ? [] : res.data
						console.log(uArr);
						console.log(serveArr);
						if (uArr) {
							uArr.map(obj => {
								serveArr.map(ele => {
									if (ele.customerAccount == obj.customerAccount) {
										return ele.rentNum = obj.rentNum, ele.overdueNum = obj.overdueNum, ele
											.lastTimeRent =
											obj.lastTimeRent
									}
								})
							});
						} else {
							uArr.map(obj => {
								serveArr.map(ele => {
									if (ele.customerAccount == obj.customerAccount) {
										return ele.rentNum = 0, ele.overdueNum = 0, ele.lastTimeRent = ''
									}
								})
							});
						}


						let newArr = serveArr.map(obj => {
							return {
								...filteredObject(obj)
							}
						})
						console.log(newArr);
						newArr.forEach(item => {
							addUser(item).then(rrs => {
								console.log(rrs);
							})
						})
					}
				}
			},
			async createDeviceType() {
				let res = await getModelList();
				if (res.code == 0) {
					this.sync_flag++;
					console.log(5);
					uni.setStorageSync('sync_flag', this.sync_flag);
					let arr = res.data == null ? [] : res.data

					arr.forEach(item1 => {
						this.tableArr.forEach(item2 => {
							if (item2.productModel == item1.productModel) {
								item1.tenantable = item2.tenantable, item1.inStore = item2.inStore, item1.reserve = item2
									.reserve
							}
						})
					})
					console.log(arr, '============');
					arr.forEach(item => {
						addDeviceType(item).then(rrs => {
							console.log(rrs);
						})
					})
				}


			},
			// 设置品类的可租数量
			settenantable(result) {
				let tempMap = {};

				// 遍历result数组，并更新tempMap
				for (let item of result) {
					if (!tempMap[item.productModel]) {
						tempMap[item.productModel] = {
							inStore: 0, // 库存
							reserve: 0, // 预留
							tenantable: 0, // 可租赁
							total: 0 // 总数量
						};
					}

					// 根据stockStatus的值更新tempMap中的相应计数
					tempMap[item.productModel].total++;
					if (item.stockStatus == 1) {
						tempMap[item.productModel].inStore++;
					} else if (item.stockStatus == 2) {
						// 假设stockStatus为2代表预留
						tempMap[item.productModel].reserve++;
					}
					// 假设所有产品都可租赁，这里只是简单地将总数赋值给tenantable
					// tempMap[item.productModel].tenantable = tempMap[item.productModel].total;
					tempMap[item.productModel].tenantable = tempMap[item.productModel].inStore + tempMap[item.productModel]
						.reserve;
				}

				// 从tempMap中生成newArr
				let newArr = [];
				for (let key in tempMap) {
					newArr.push({
						productModel: key,
						inStore: tempMap[key].inStore,
						reserve: tempMap[key].reserve,
						tenantable: tempMap[key].tenantable
					});
				}
				return newArr

			},
			async createDevice() {

				let res = await liststockbind();
				if (res.code == 0) {
					this.sync_flag++;
					console.log(6);
					uni.setStorageSync('sync_flag', this.sync_flag);

					let newArr = res.data == null ? [] : res.data
					let arr = newArr.map(obj => {
						// 计数器30000 - 49999 
						let counter = 30000;
						let productProperty = JSON.parse(obj.productProperty);
						if (productProperty.counts) {
							counter = productProperty.counts;
						}

						return obj.counter = counter, {
							...filteredObject(obj)
						}
					});
					console.log(arr);
					this.tableArr = this.settenantable(arr)
					console.log(this.tableArr);
					// tableArr.forEach(item =>{
					// 	addDeviceType(item)
					// })
					this.createDeviceType()
					arr.forEach(item => {
						addDevice(item).then(rrs => {
							console.log(rrs);
						})
					})
				}



			},
			async createPrice() {
				let res = await leaFixPricePage();
				if (res.code == 0) {
					this.sync_flag++;
					console.log(7);
					console.log(res);
					uni.setStorageSync('sync_flag', this.sync_flag);

					if (res.data != null && res.data.records.length > 0) {
						let arr = res.data.records.map(item => ({
							productModel: item.productModel,
							priceGroup: item.priceGroup,
							agencySecurityDeposit: item.agencySecurityDeposit,
							priceModel: item.priceModel,
							commission: item.commission,
						}))
						console.log(arr);
						arr.forEach(item => {
							addPrice(item).then(rrs => {
								console.log(rrs);
							})
						})
					}

				}
			},
			async createMoney() {
				let res = await gtTotal();
				console.log(res);
				if (res.code == 0) {
					this.sync_flag++;
					console.log(8);
					uni.setStorageSync('sync_flag', this.sync_flag);
					let arr = [{
						customerAccount: res.data.customerAccount,
						onMoney: res.data.amountOnline,
						offMoney: res.data.amountOffline,
						amountTotal: res.data.amountTotal,
						amountTurnover: res.data.amountTurnover,
						amountIncome: res.data.amountIncome,
						amountDeposit: res.data.amountDeposit
					}]

					arr.forEach(item => {
						addOrUpdateMoney(item)
					})
				}

			},

			async openDB() {

				let res = await this.$sql.isOpen(this.database);
				console.log(res);
				if (res.data) return
				let res1 = await this.$sql.openDB(this.database);
				console.log(res1);

			},
			// 拉取lease 备份数据
			async createLease() {
				let res = await initdatas();
				console.log(res);

				if (res.code == 0) {
					this.sync_flag++;
					console.log(9);
					uni.setStorageSync('sync_flag', this.sync_flag);
				}

				if (res.data.lease) {


					res.data.lease.forEach(item => {
						delete item.synAccount
						console.log(item);
						addLease(item).then(rrs => {
							console.log(rrs);
						})
					})
				}

				// await delLease();
				// let res = await leasebdatas();
				// let dRes = await getInStoreArr();
				// console.log(res, dRes);
				// res.data.map(item => {
				// 	let index = dRes.data.findIndex(ele => {
				// 		return ele.productId == item.productId
				// 	})
				// 	if (index > -1) { //已设备状态为准
				// 		return item.leaseStatus = dRes.data[index].stockStatus
				// 	}
				// })

				// res.data.forEach((item, ind) => {
				// 	let index = dRes.data.findIndex(ele => {
				// 		return ele.productId == item.productId
				// 	})

				// 	if (index == -1) {
				// 		res.data.splice(ind, 1);
				// 	}
				// })
				// console.log('================', res);


			},
			createDB() {
				// 创建表
				cratetable().then(async res => {
					console.log(res);
					// 添加数据
					await this.createUser();
					await this.createDevice();
					await this.createPrice();
					await this.createMoney();
					await this.createLease();

					let timer = setTimeout(() => {
						clearTimeout(timer)
						uni.hideLoading();
						console.log(this.sync_flag);
						if (this.sync_flag == 9) {

							uni.switchTab({
								url: '/pages/home/home'
							})
						} else {
							console.log('接口未完成');

							// uni.showToast({
							// 	title:'Internet is bad, Try again later',
							// 	icon:'none',
							// })
							uni.showLoading({
								title: 'Loading',
								icon: 'loading'
							})
							logout().then(res => {
								uni.hideLoading()
								console.log(res);
								if (res.code == 0) {

									let lang = uni.getStorageSync('lang')
									uni.clearStorageSync();
									uni.setStorageSync('lang', lang);


								}
							})

						}

					}, 1000)
				})

			},

		},
		computed: {
			...mapState({
				skin: state => state.theme.skin
			})

		},
		mounted() {

		},
		created() {

		}
	}
</script>


<style lang="scss" scoped>
	.login {
		width: 100%;
		height: 100%;
		padding: 16px;
		box-sizing: border-box;
		position: relative;




		.loginBox {
			width: 100%;
			height: 200px;
			display: flex;
			align-items: flex-start;

			.loginList {
				width: 50px;
				height: 50px;
				background-color: var(--subjectColor);
				display: block;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-right: 20px;
			}
		}

		.headline {
			width: 100%;
			height: 148px;
			padding: 44px 16px 16px;
			box-sizing: border-box;
			font-size: 24px;
			margin-top: 36px;
		}

		.formBox {
			padding: 0 16px;
			box-sizing: border-box;
			position: relative;


			.u-demo-block__content {
				background-color: #f8f8f8;
				border-radius: 4px;
				margin-bottom: 20px;
				margin-top: 10px;
				height: 40px;
				padding: 8px;
				box-sizing: border-box;

			}





			.sendCode {
				font-size: 14px;
			}

			.errInfo {
				font-size: $uni-fz-12;
				color: $uni-color-red;
				line-height: 1.5;
			}


			.passIcon {
				color: var(--subtopicTextColor) !important;
				font-size: 18px;
			}
		}

		.modelChange {
			width: 100%;
			height: 53px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: var(--subjectColor);
			font-size: 14px;
			padding: 0 16px;
			box-sizing: border-box;
			margin-top: 16px;
		}

		.btnModule {
			width: 100%;
			height: 44px;
			box-sizing: border-box;
			margin-top: 16px;
		}

		.footer {
			width: 100%;
			position: fixed;
			left: 0;
			bottom: 16px;
			height: 57px;

			.tips {
				text-align: center;

				.tipsColor {
					color: var(--subjectColor);
				}
			}
		}

	}
</style>